/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
    /**
 * @param {number[]} height
 * @return {number}
 */
    var trap = function (height) {
        if (height.length < 3) return 0
        let left = -1;
        let right = height.length;
        let leftNum = 0;
        let rightNum = 0;
        let num = 0
        while (leftNum == 0) {
            left++
            leftNum = Math.max(leftNum, height[left])

        }
        while (rightNum == 0 && right > left) {
            right--
            rightNum = Math.max(rightNum, height[right])

        }
        // leftNum = 1 //左边的最高值
        // rightNum = 1 //右边的最高值
        // left = 1
        // right = 11
        console.log(leftNum, rightNum);
        console.log(left, right);
        while (left < right) {

            if (leftNum > rightNum) {
                right--
                if (height[right] < rightNum) {
                    // rightNum 不变
                    // 可以计算雨水
                    num = num + rightNum - height[right]

                } else {
                    rightNum = height[right]
                }
            } else {
                left++
                if (height[left] < leftNum) {
                    // leftNum 不变
                    // 可以计算雨水
                    num = num + leftNum - height[left]

                } else {
                    leftNum = height[left]
                }

            }

        }
        return num
    };
    let a = trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 2])
    console.log(a);
};
// 单调栈写法
; (function () {
    //return
    /**
   * @param {number[]} height
   * @return {number}
   */
    var trap = function (height) {
        let stack = []
        let result = 0

        for (let index = 0; index < height.length; index++) {
            const num = height[index];
            while (stack.length > 1 && height[stack.at(-1)] < num) {
                let curIdx = stack.pop()
                let curNum = height[curIdx]
                let leftIdx = stack.at(-1)
                let leftNum = height[leftIdx]
                let minNum = Math.min(leftNum, num)
                result = result + (index - leftIdx - 1) * (minNum - curNum)
            }

            if (stack.length === 1 && height[stack[0]] < num) {
                stack[0] = index
            } else {
                stack.push(index)
            }

        }

        return result
    };
})();